package com.example.alarm.mvvm.activity

import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Rect
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.alarm.R
import com.example.alarm.mvvm.bean.ReqAttachmentBean
import com.example.login.mvvm.viewmodel.AlarmViewModel
import com.gsafety.library.Exts.Ext
import com.gsafety.libraryktx.adapter.RvAttachPicAdapter
import com.gsafety.libraryktx.base.BaseActivity
import com.gsafety.libraryktx.bean.AttachBean
import com.gsafety.libraryktx.bean.LoadState
import com.gsafety.libraryktx.bean.WarnData
import com.gsafety.libraryktx.config.Constant
import com.gsafety.libraryktx.config.Constant.Companion.CODE_FEEDBACK_WC
import com.gsafety.libraryktx.config.Constant.Companion.DEAL_STATE_FEEDBACK
import com.gsafety.libraryktx.config.Constant.Companion.DEAL_STATE_FINISH
import com.gsafety.libraryktx.expand.create
import com.gsafety.libraryktx.expand.toast
import com.gsafety.libraryktx.manager.UserManager
import com.gsafety.libraryktx.util.AppUtil
import com.gsafety.xuzhou.bean.SelectOpeListener
import com.gsafety.xuzhou.util.Glide4Engine
import com.gsafety.xuzhou.util.SizeUtils
import com.lxj.matisse.CaptureMode
import com.lxj.matisse.Matisse
import com.lxj.matisse.MimeType
import kotlinx.android.synthetic.main.alarm_feedback_actiivty.*
import me.rosuh.filepicker.config.FilePickerManager
import okhttp3.MultipartBody
import okhttp3.RequestBody
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.util.*

class FeedbackActivity:BaseActivity() {
    private var mPicAdapter: RvAttachPicAdapter? = null
    var mPicList = mutableListOf<AttachBean>()
    val REQ_CHOOSE_PIC = 1001
    val REQ_CHOOSE_FILE = 1002
    val REQ_GALLERY = 1003
    private var type:String?= ""
    private lateinit var mv: AlarmViewModel
    var attachments:ReqAttachmentBean = ReqAttachmentBean()
    var recordsBean : WarnData.RecordsBean? = null
    var dealType = DEAL_STATE_FINISH
    override fun initView() {
        mv = AlarmViewModel()
        mv = create(AlarmViewModel::class)
        mPicAdapter = RvAttachPicAdapter(mPicList)
        mPicAdapter?.setListener(object : SelectOpeListener {
            override fun onCheckChange(count: Int) {
//                    GalleryActivity.startIntent((context as ContextThemeWrapper).baseContext as Activity, mPresenter!!.getRealPicList(), count, true, AlarmDetailActivity.REQ_GALLERY)
            }
        })
        mPicAdapter?.setFooterView(
            LayoutInflater.from(this).inflate(
                R.layout.alarm_add_pic_layout,
                mPicAdapter?.footerLayout,
                false
            )
        )
        mPicAdapter?.footerLayout?.setOnClickListener{
            choosePic()
        }
        rlv_file_list.adapter = mPicAdapter
        var gridLayoutManager = GridLayoutManager(this, 4)
        rlv_file_list.layoutManager = gridLayoutManager
        findViewById<TextView>(R.id.title_name).text = "预警反馈"
        rlv_file_list.addItemDecoration(object : RecyclerView.ItemDecoration() {

            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                if (parent.getChildAdapterPosition(view) / 4 != 0) {
                    outRect.top = Ext.dp2px(this@FeedbackActivity, 16)
                }
            }
        })
        findViewById<TextView>(R.id.title_name).text = "预警反馈"
        var hasFinish:Boolean = UserManager.getInstance().appModelCodes()?.contains(CODE_FEEDBACK_WC)!!
        rb_has_finish.visibility = if(hasFinish) View.VISIBLE else View.GONE
        dealType = if(hasFinish) DEAL_STATE_FINISH else DEAL_STATE_FEEDBACK
        rb_has_finish.setOnCheckedChangeListener{
            btn, checked->
            dealType = if(checked) DEAL_STATE_FINISH else DEAL_STATE_FEEDBACK
        }
    }

    override fun initData() {
        type = intent.getStringExtra("type")
        recordsBean = intent.getSerializableExtra("records") as WarnData.RecordsBean?
        if(type == DEAL_STATE_FEEDBACK){
            tv_alarm_info.visibility = View.GONE
            et_alarm_info.visibility = View.GONE
        }

        tv_sure.setOnClickListener{
            if(et_deal_info.text.toString().isNullOrEmpty()){
                toast("请输入处置情况")
                return@setOnClickListener
            }
//            if(et_alarm_info.text.toString().isNullOrEmpty()){
//                toast("请输入预警原因")
//                return@setOnClickListener
//            }
            showDia("上传中...")
            if(mPicList.size == 0){
                reqFeedback()
            }else{
                val builder = MultipartBody.Builder()
                mPicList.forEach {
                    var file = File(it.id)
                    //构建requestbody
                    val requestFile: RequestBody = RequestBody.create(MultipartBody.FORM, file)
                    builder.addFormDataPart("files", file.getName(), requestFile) // 批示
                }
                mv.upload(builder.build().parts)
            }
        }

        mv.uploadValue.observe(this@FeedbackActivity, androidx.lifecycle.Observer {
            it.forEach {
                attachments.to1.add(it.pid.toString())
            }
            reqFeedback()
        })
        dealData()

        mv.uploadState.observe(this, androidx.lifecycle.Observer {
            when(it) {
                is LoadState.Success -> {
                    disDia()
                }
                is LoadState.Fail-> {
                    disDia()
                }
            }
        })
    }

    fun reqFeedback(){
        var userName = UserManager.getInstance().getUser()?.userName + ""
        var  procUnit = UserManager.getInstance().getUser()?.orgName + ""
        mv.addDisposalProc(
            recordsBean?.pid!!,
            "",
            dealType,
            recordsBean?.adtevtStatus.toString(),
            et_deal_info.text.toString(),
            procUnit,
            userName,
            et_alarm_info.text.toString(),
            AppUtil.getYmdHmssSSS(
                Date()
            ),
            attachments
        )
    }

    fun dealData(){
        mv.addDisposalProcValue.observe(this, androidx.lifecycle.Observer {
            if (!mv.addDisposalProcValue.value.isNullOrEmpty()) {
                Toast.makeText(this, mv.addDisposalProcValue.value, Toast.LENGTH_SHORT).show()
                setResult(Constant.DEAL_RES_OK_CODE)
                disDia()
                finish()
            }
        })
    }

    override fun getLayoutId(): Int {
        return R.layout.alarm_feedback_actiivty
    }

    private fun choosePic() {
        var count = mPicAdapter!!.maxCount - mPicList.size
        if (count > 0) {
            Matisse.from(this)
                .choose(
                    MimeType.of(
                        MimeType.JPEG,
                        MimeType.PNG,
                        MimeType.BMP,
                        MimeType.GIF,
                        MimeType.MP4
                    )
                )
                .countable(true)
                .capture(true, CaptureMode.All)//是否显示拍摄按钮，默认不显示
                .maxSelectable(count)
                .gridExpectedSize(SizeUtils.dp2px(this, 100f))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(1.0f)
                .imageEngine(Glide4Engine())
                .forResult(REQ_CHOOSE_PIC)
        } else {
            Toast.makeText(this, "图片数量已达到上限", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (requestCode == REQ_CHOOSE_PIC && resultCode == RESULT_OK) {
                var capturePath: String? = null
                var videoPath: String? = null
                var cropPath: String? = null
                if (Matisse.obtainCaptureVideoResult(data).also { videoPath = it } != null) {
                    //录制的视频
                    capturePath = Matisse.obtainCaptureImageResult(data)
                    var capList = mutableListOf<String>(videoPath!!)
                    setAttachDatas(capList)
                } else if ((Matisse.obtainCaptureImageResult(data).also { capturePath = it }) != null) {
//                    captureText.setText("拍照路径：$capturePath")
                    var capList = mutableListOf<String>(capturePath!!)
                    setAttachDatas(capList)
                } else if ((Matisse.obtainCropResult(data).also { cropPath = it }) != null) {
//                    var s: String = "裁剪的路径：$cropPath"
//                    s += "\n 原图路径：" + Matisse.obtainSelectPathResult(data)[0]
                } else {
                    var uri = Matisse.obtainSelectUriResult(data)
                    var paths = Matisse.obtainSelectPathResult(data)
                    setAttachDatas(paths)
                    Log.e(
                        "OnActivityResult",
                        "originalState: " + Matisse.obtainOriginalState(data).toString()
                    )
                }
            } else if (requestCode == REQ_CHOOSE_FILE) {
                var selData = FilePickerManager.obtainData()
                if (selData != null) {
//                    selData = selData.filter {
//                        AppUtil.isNeedFile(it)
//                    }
                }
//                mPresenter!!.addFileList(selData)
//                mFileAdapter?.setNewData(mPresenter!!.getFileList())
            } else if (requestCode == REQ_GALLERY) {
//                val intentData = data?.getSerializableExtra(Constant.WEB_URL)
//                if (intentData != null) {
//                    val data = intentData as List<AttachBean>
//                    mPresenter!!.replacePicList(data)
//                    dealDialog?.setNewData(mPresenter!!.getPicList())
//                }
            }
        }
    }

    private fun setAttachDatas(list: List<String>) {
        addPicList(list)
        if(mPicList.size>=mPicAdapter!!.maxCount){
            mPicAdapter?.footerLayout?.visibility = View.GONE
        }else{
            mPicAdapter?.footerLayout?.visibility = View.VISIBLE
        }
        mPicAdapter?.setNewData(mPicList)
    }

    private fun compressPicList(selData: List<String>?) {
        if (selData != null) {
            var dealList = mutableListOf<String>()
            Luban.with(this)
                .load<Any>(selData)
                .ignoreBy(1024)
                .setTargetDir(Constant.PICTURES_DIR)
                .setCompressListener(object : OnCompressListener {
                    override fun onStart() {
                        showDia("图片压缩中...")
                    }

                    override fun onSuccess(file: File) {
                        dealList.add(file.toString())
                        if (dealList.size == selData.size) {
                            addPicList(dealList)
                            disDia()
                            mPicAdapter?.setNewData(mPicList)
//                            mPresenter!!.addPicList(dealList)
//                            dealDialog?.setNewData(mPresenter!!.getPicList())
                        }
                    }

                    override fun onError(e: Throwable) {
                        disDia()
                        showToast(e.message ?: "图片压缩失败")
                    }
                }).launch()
        }
    }

    fun addPicList(selData: List<Any>) {
        if (selData != null && selData.isNotEmpty()) {
            selData.forEach {
                if (it is String) {
                    var type = it.substring(it.lastIndexOf(".") + 1)
                    val item = AttachBean(it, "", type)
                    if (mPicList?.contains(item) != true) {
                        mPicList?.add(item)
                    }
                } else if (it is AttachBean) {
                    if (mPicList?.contains(it) != true) {
                        mPicList?.add(it)
                    }
                }
            }
        }
    }
}